<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from './stores/user'
import TopNavbar from './components/TopNavbar.vue'
import LoginModal from './components/LoginModal.vue'

// 响应式数据
const videoLoaded = ref(false)
const showLoginModal = ref(false)
const loginModalMode = ref('login') // 'login' or 'register'

// 路由和用户状态管理
const router = useRouter()
const userStore = useUserStore()

// 组件挂载时初始化用户信息
onMounted(async () => {
  // 本地恢复
  userStore.initUserInfo()
  // 同步后端 Session 登录态（若已有会话则填充 userInfo）
  try {
    await userStore.getCurrentUser()
  } catch (e) {
    // 忽略错误，由 store 内部处理清理
  }
  
  // 监听路由守卫触发的登录事件
  window.addEventListener('show-login-modal', () => {
    showLogin()
  })
})

// 处理导航切换
const handleNavigation = (page) => {
  // 使用路由跳转
  router.push(`/${page === 'home' ? '' : page}`)
}

// 显示登录弹窗
const showLogin = () => {
  loginModalMode.value = 'login'
  showLoginModal.value = true
}

// 显示注册弹窗
const showRegister = () => {
  loginModalMode.value = 'register'
  showLoginModal.value = true
}

// 关闭登录弹窗
const closeLoginModal = () => {
  showLoginModal.value = false
}

// 登录成功处理
const handleLoginSuccess = (result) => {
  console.log('登录成功:', result)
  // 更新用户store状态
  userStore.setUserInfo(result.data)
  // 关闭登录弹窗
  closeLoginModal()
  // 可以在这里添加成功提示（使用更好的UI提示而不是alert）
  console.log('欢迎回来，', result.data.userName || result.data.userAccount)
}

// 用户注销
const handleLogout = async () => {
  if (confirm('确定要退出登录吗？')) {
    await userStore.logout()
    console.log('用户已注销')
  }
}

// 视频事件处理函数
const handleVideoError = (event) => {
  console.error('视频加载错误:', event)
}

const handleVideoLoadStart = () => {
  console.log('视频开始加载')
}

const handleVideoCanPlay = () => {
  console.log('视频可以播放')
}

const handleVideoLoaded = () => {
  console.log('视频数据加载完成')
  videoLoaded.value = true
}
</script>

<template>
  <div id="app">
    <!-- 全屏背景 -->
    <div class="background-container">
      <!-- 视频背景 -->
      <video 
        autoplay 
        muted 
        loop 
        playsinline
        preload="metadata"
        class="background-video"
        @error="handleVideoError"
        @loadstart="handleVideoLoadStart"
        @canplay="handleVideoCanPlay"
        @loadeddata="handleVideoLoaded"
      >
        <source src="/img/1.mp4" type="video/mp4">
      </video>
      
      <!-- 备用静态背景 -->
      <div class="fallback-background" :class="{ active: !videoLoaded }"></div>
      
      <!-- 背景遮罩 -->
      <div class="background-overlay"></div>
    </div>
    
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 顶部导航栏 -->
      <TopNavbar 
        @navigate="handleNavigation" 
        @show-login="showLogin"
        @show-register="showRegister"
        @logout="handleLogout"
      />
      
      <!-- 内容展示区 -->
      <router-view />
    </div>
    
    <!-- 登录注册弹窗 -->
    <LoginModal 
      :visible="showLoginModal"
      :mode="loginModalMode"
      @close="closeLoginModal"
      @success="handleLoginSuccess"
    />
  </div>
</template>

<style scoped>
#app {
  position: relative;
  width: 100%;
  min-height: 100vh;
  overflow-x: hidden;
}

/* 背景容器样式 */
.background-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -2;
  overflow: hidden;
}

.background-video {
  position: absolute;
  top: 50%;
  left: 50%;
  min-width: 100%;
  min-height: 100%;
  width: auto;
  height: auto;
  transform: translate(-50%, -50%);
  object-fit: cover;
  opacity: 1;
  transition: opacity 0.5s ease;
}

.background-video:error {
  opacity: 0;
}

/* 备用静态背景 */
.fallback-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    135deg,
    #667eea 0%,
    #764ba2 25%,
    #f093fb 50%,
    #f5576c 75%,
    #4facfe 100%
  );
  background-size: 400% 400%;
  animation: gradientShift 15s ease infinite;
  opacity: 0;
  transition: opacity 0.5s ease;
}

.fallback-background.active {
  opacity: 1;
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}
</style>
